package com.chikitbd.freev2ray.service;

import com.chikitbd.common.Crawler;
import com.chikitbd.common.PropertiesLoader;
import com.chikitbd.freev2ray.bean.guinconfig.V2RayConfig;
import com.chikitbd.freev2ray.bean.guinconfig.Vmess;
import com.chikitbd.common.Util;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class V2RayServiceImpl implements Crawler {

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 主方法入口
     *
     * @param args
     */
    public static void main(String[] args) {
        V2RayServiceImpl v2RayServiceImpl = new V2RayServiceImpl();
        try {
            v2RayServiceImpl.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 程序入口
     * @throws IOException
     */
    public void start() throws IOException {
        String originalConfig = "";
        HtmlPage page;

        // FreeV2Ray 的地址
        String url = PropertiesLoader.V2RAY_URL;
        // V2Ray的目录
        String v2rayPath = PropertiesLoader.V2RAY_PATH + PropertiesLoader.GUI_N_CONFIG;

        try (WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
            page = webClient.getPage(url);
            originalConfig = this.readConfig(PropertiesLoader.V2RAY_CONFIG_CLASS_PATH);
            this.writeConfig(originalConfig, page, v2rayPath);
        }
    }


    /**
     * 读取编译目录的guiNConfig.json配置文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public String readConfig(String filePath) throws IOException {
        if(filePath.startsWith("/") || filePath.startsWith("\\")){
                filePath = filePath.substring(1, filePath.length());
        }
        return Util.readFile(filePath);
    }


    /**
     * 写入新的配置文件
     * @param originalConfig
     * @param page
     * @param filePath
     * @return
     * @throws IOException
     */
    public boolean writeConfig(String originalConfig, HtmlPage page, String filePath) throws IOException {
        boolean flag = false;
        // 读取原来的配置文件, 通过Gson转化为JavaBean
        V2RayConfig v2RayConfig = gson.fromJson(originalConfig.toString(), V2RayConfig.class);

        // 爬虫, 获得服务器信息, 吸入ConfigsList
        this.setConfig(v2RayConfig, page);

        // 将新的配置文件通过Gson转化为JSON格式文本
        String crawlerJsonResult = gson.toJson(v2RayConfig);

        boolean result = Util.writeFile(crawlerJsonResult, filePath);
        if (result) {
            Util.printfSuccess("V2Ray-FreeV2Ray");
        }
        return flag;
    }


    /**
     * 从爬取的页面获取相关的V2Ray服务器
     * @param guiNConfig
     * @param page
     */
    public void setConfig(V2RayConfig guiNConfig, HtmlPage page) {

        try {
            HtmlElement ip_div = page.getHtmlElementById("ip");
            HtmlElement port_div = page.getHtmlElementById("port");
            HtmlElement uuid_div = page.getHtmlElementById("uuid");

            String ip = ip_div.asText();
            String port = port_div.asText();
//            String uuid = UUID.randomUUID().toString().toLowerCase();
            String uuid = uuid_div.asText();

            List<Vmess> vmesss = guiNConfig.getVmess();
            if(vmesss.size() > 0 ){
//                Vmess vmessTmp = vmesss.get(0);
                Vmess vmessTmp = new Vmess();
                vmessTmp.setAddress(ip);
                vmessTmp.setId(uuid);
                vmessTmp.setPort(Integer.valueOf(port));
                vmessTmp.setAlterId(1);
                vmessTmp.setRequestHost("microsoft.com");
                vmesss.add(vmessTmp);
            }else{
                System.out.println("配置读取出错。");
                System.exit(0);
            }
        }finally {
            page.cleanUp();
        }
    }

}
